package com.hdsx.netty.rpcserver.bio.handle;

import com.hdsx.netty.protocol.BasicProtocol;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

/**
 * @author 占贤银
 * time 2024/8/8 23:39
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class BusinessHandler implements Runnable {

    private Socket socket;

    private Map<String, Object> registerMaps;

    public BusinessHandler(Socket socket, Map<String, Object> registerMaps) {
        this.socket = socket;
        this.registerMaps = registerMaps;
    }

    @Override
    public void run() {
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            // 获取客户端传送过来的数据
            ois = new ObjectInputStream(socket.getInputStream());
            BasicProtocol protocol = (BasicProtocol) ois.readObject();
            Object targetObj = registerMaps.get(protocol.getClassName());
            Class<?> aClass = targetObj.getClass();
            Method method = aClass.getMethod(protocol.getMethodName(), protocol.getParameterType());
            Object result = method.invoke(targetObj, protocol.getParameterValues());
            oos = new ObjectOutputStream(socket.getOutputStream());
//            if (result instanceof String) {
//                oos.writeChars((String) result);
//            } else if (result instanceof Object) {
//                oos.writeObject(result);
//            }
            oos.writeObject(result);
            oos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != ois) {
                try {
                    ois.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != oos) {
                try {
                    oos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
